<template>
  <div class="system-management">
    <div class="page-header">
      <h1>系统管理</h1>
      <p>系统配置和管理功能中心</p>
    </div>

    <!-- 系统状态概览 -->
    <div class="system-status">
      <h2 class="section-title">系统状态</h2>
      <el-row :gutter="20">
        <el-col :span="6" :xs="12">
          <div class="status-card">
            <div class="status-icon">
              <el-icon size="32" color="#67c23a"><CircleCheck /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">正常</div>
              <div class="status-label">系统运行</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12">
          <div class="status-card">
            <div class="status-icon">
              <el-icon size="32" color="#409eff"><DataBoard /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ formatUptime(systemInfo.uptime) }}</div>
              <div class="status-label">运行时间</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12">
          <div class="status-card">
            <div class="status-icon">
              <el-icon size="32" color="#e6a23c"><Connection /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ systemInfo.activeConnections }}</div>
              <div class="status-label">活跃连接</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12">
          <div class="status-card">
            <div class="status-icon">
              <el-icon size="32" color="#f56c6c"><Monitor /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-value">{{ systemInfo.memoryUsage }}%</div>
              <div class="status-label">内存使用</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
      <h2 class="section-title">快速操作</h2>
      <el-row :gutter="20">
        <el-col :span="8" :xs="24">
          <div class="action-card" @click="goToLogs">
            <div class="action-icon">
              <el-icon size="48" color="#409eff"><Document /></el-icon>
            </div>
            <div class="action-content">
              <h3>操作日志</h3>
              <p>查看系统操作记录和审计日志</p>
              <div class="action-stats">
                <span>今日操作：{{ todayOperations }}次</span>
              </div>
            </div>
            <div class="action-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </el-col>
        <el-col :span="8" :xs="24">
          <div class="action-card" @click="handleSystemConfig">
            <div class="action-icon">
              <el-icon size="48" color="#67c23a"><Setting /></el-icon>
            </div>
            <div class="action-content">
              <h3>系统配置</h3>
              <p>管理系统参数和应用配置</p>
              <div class="action-stats">
                <span>配置项：{{ configCount }}个</span>
              </div>
            </div>
            <div class="action-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </el-col>
        <el-col :span="8" :xs="24">
          <div class="action-card" @click="handleDataBackup">
            <div class="action-icon">
              <el-icon size="48" color="#e6a23c"><FolderOpened /></el-icon>
            </div>
            <div class="action-content">
              <h3>数据备份</h3>
              <p>数据库备份和恢复管理</p>
              <div class="action-stats">
                <span>最后备份：{{ lastBackupTime }}</span>
              </div>
            </div>
            <div class="action-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 管理员信息 -->
    <div class="admin-info">
      <h2 class="section-title">管理员信息</h2>
      <div class="content-card">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="当前登录">{{ adminInfo.nickname }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ adminInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="adminInfo.role === 'super_admin' ? 'danger' : 'primary'">
              {{ adminInfo.role === 'super_admin' ? '超级管理员' : '管理员' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ formatDate(adminInfo.lastLoginTime) }}</el-descriptions-item>
          <el-descriptions-item label="登录IP">{{ adminInfo.lastLoginIp }}</el-descriptions-item>
          <el-descriptions-item label="登录次数">{{ adminInfo.loginCount }}次</el-descriptions-item>
        </el-descriptions>
        
        <div class="admin-actions">
          <el-button type="primary" @click="handleChangePassword">
            <el-icon><Lock /></el-icon>
            修改密码
          </el-button>
          <el-button type="warning" @click="handleClearCache">
            <el-icon><Delete /></el-icon>
            清理缓存
          </el-button>
          <el-button type="danger" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminInfo, getSystemInfo } from '@/api'

const router = useRouter()

// 响应式数据
const systemInfo = reactive({
  uptime: 0,
  activeConnections: 0,
  memoryUsage: 0
})

const adminInfo = reactive({
  username: '',
  nickname: '',
  role: '',
  lastLoginTime: '',
  lastLoginIp: '',
  loginCount: 0
})

const todayOperations = ref(156)
const configCount = ref(42)
const lastBackupTime = ref('2小时前')

// 加载系统信息
const loadSystemInfo = async () => {
  try {
    const response = await getSystemInfo()
    if (response && response.success) {
      Object.assign(systemInfo, response.data)
    }
  } catch (error) {
    // 使用模拟数据
    Object.assign(systemInfo, {
      uptime: 86400000, // 1天
      activeConnections: 23,
      memoryUsage: 65
    })
  }
}

// 加载管理员信息
const loadAdminInfo = async () => {
  try {
    const response = await getAdminInfo()
    if (response && response.success) {
      Object.assign(adminInfo, response.data)
    }
  } catch (error) {
    console.error('Load admin info failed:', error)
  }
}

// 跳转到操作日志
const goToLogs = () => {
  router.push('/system/logs')
}

// 系统配置
const handleSystemConfig = () => {
  ElMessage.info('系统配置功能开发中...')
}

// 数据备份
const handleDataBackup = () => {
  ElMessage.info('数据备份功能开发中...')
}

// 修改密码
const handleChangePassword = () => {
  ElMessage.info('修改密码功能开发中...')
}

// 清理缓存
const handleClearCache = async () => {
  try {
    await ElMessageBox.confirm('确定要清理系统缓存吗？', '确认操作', {
      type: 'warning'
    })
    
    // 模拟清理缓存
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('缓存清理完成')
  } catch (error) {
    // 用户取消操作
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认退出', {
      type: 'warning'
    })
    
    localStorage.removeItem('admin_token')
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消操作
  }
}

// 格式化运行时间
const formatUptime = (milliseconds: number) => {
  const seconds = Math.floor(milliseconds / 1000)
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (days > 0) {
    return `${days}天${hours}小时`
  } else if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 格式化日期
const formatDate = (date: Date | string) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

// 页面加载
onMounted(() => {
  loadSystemInfo()
  loadAdminInfo()
})
</script>

<style scoped>
.system-management {
  padding: 0;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.system-status {
  margin-bottom: 32px;
}

.status-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
}

.status-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.status-icon {
  flex-shrink: 0;
}

.status-info {
  flex: 1;
}

.status-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.status-label {
  font-size: 14px;
  color: #909399;
}

.quick-actions {
  margin-bottom: 32px;
}

.action-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.action-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.action-icon {
  flex-shrink: 0;
}

.action-content {
  flex: 1;
}

.action-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.action-content p {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.5;
}

.action-stats {
  font-size: 12px;
  color: #909399;
}

.action-arrow {
  flex-shrink: 0;
  color: #c0c4cc;
  transition: all 0.3s ease;
}

.action-card:hover .action-arrow {
  color: #409eff;
  transform: translateX(4px);
}

.admin-info {
  margin-bottom: 32px;
}

.admin-actions {
  margin-top: 20px;
  text-align: right;
}

.admin-actions .el-button {
  margin-left: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .status-card {
    padding: 16px;
    gap: 12px;
  }
  
  .status-value {
    font-size: 20px;
  }
  
  .action-card {
    padding: 20px;
    gap: 16px;
  }
  
  .action-content h3 {
    font-size: 16px;
  }
  
  .admin-actions {
    text-align: left;
  }
  
  .admin-actions .el-button {
    margin: 0 8px 8px 0;
  }
}
</style>
